# 检查所有节点是否可访问，用于快速检查服务是否可用
# 原理 ：先从数据库读取所有可用的代理，然后http访问测试

import sql
import requests
import threading
import os


from colorama import init,Fore,Back,Style

init(autoreset=True)



dict_data = sql.dict_data
list_ok = []
list_bad = []



# 单个请求
def http_get_onehost(url,name):
    global list_ok
    global list_bad

    try:
        r = requests.get(url, timeout=2)
        str_ok = str(round(r.elapsed.total_seconds(), 1)) + " " + str(r.status_code) + " "+ str(name[0]).ljust(18,chr(12288))+"  "+str(name[1][0]).ljust(18)+str(name[1][1]).ljust(6)+ str(name[1][2])
        list_ok.append(str_ok)
    except requests.exceptions.RequestException as e:
        str_bad = "ERR     " + str(name[0]).ljust(18,chr(12288))+"  "+ str(name[0]).ljust(18,chr(12288)) + "  " + str(name[1][0]).ljust(18) + str(name[1][1]).ljust(6) + str(name[1][2])


        list_bad.append(str_bad)



#多线程 自定义函数
def start():
    print("开始访问测试......")
    threads = [];
    for i in dict_data.items():
        url = "http://" + str(i[1][0]) + ":" + str(i[1][1])  # i () ('四川xx', ['10.9.5.2', '8200'])
        thread = threading.Thread(target=http_get_onehost, args=(url,i))
        threads.append(thread)
    for t in threads:
        t.start();
    for t in threads:
        t.join();


def show():
    print("测试成功")
    print("     时间 状态 名称                            ip                端口   服务器")
    for i in list_ok:
        print("\033[32m" + "     " + i + "\033[0m")

    print("测试失败")
    for i in list_bad:
        print("\033[31m" + "     " + i + "\033[0m")

start()
show()


os.system('pause')